﻿﻿// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System;
using Microsoft.ServiceBus.Messaging;

namespace Nardax.Azure.ServiceBus
{
    public class MessageReceiverWrapper : IMessageReceiver
    {
        private readonly MessageReceiver _messageReceiver;
        private bool _isReceiving;
        private string _namespace;

        public MessageReceiverWrapper(string connectionString, string path)
        {
            var messagingFactory = MessagingFactory.CreateFromConnectionString(connectionString);
            _namespace = messagingFactory.Address.DnsSafeHost;
            _messageReceiver = messagingFactory.CreateMessageReceiver(path);
        }

        public IAsyncResult BeginReceive(TimeSpan serverWaitTime, AsyncCallback callback, object state)
        {
            if (_isReceiving)
            {
                return null;
            }

            _isReceiving = true;

            return _messageReceiver.BeginReceive(serverWaitTime, callback, state);
        }

        public BrokeredMessage EndReceive(IAsyncResult result)
        {
            try
            {
                var message = _messageReceiver.EndReceive(result);
                return message;
            }
            finally
            {
                _isReceiving = false;
            }
        }

        public void Close()
        {
            _messageReceiver.Close();
        }

        public int PrefetchCount
        {
            get { return _messageReceiver.PrefetchCount; }
            set { _messageReceiver.PrefetchCount = value; }
        }

        public bool IsEmpty { get; set; }

        public string Namespace
        {
            get { return _namespace; }
        }

        public string Path
        {
            get { return _messageReceiver.Path; }
        }
    }
}